package com.masterclient.app.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.masterclient.app.R;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;

public class TagTextView extends android.support.v7.widget.AppCompatTextView {

    private StringBuffer content_buffer;

    private TextView tv_tag;
    private ImageView img_tag;

    private View view;//标签布局的最外层布局

    private Context mContext;

//必须重写所有的构造器，否则可能会出现无法inflate布局的错误！

    public TagTextView(Context context) {

        super(context);

        mContext = context;

    }


    public TagTextView(Context context, AttributeSet attrs) {

        super(context, attrs);

        mContext = context;

    }


    public TagTextView(Context context, AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

        mContext = context;

    }

    //新人价
    public void setContentAndTag(String content, List<String> tags, boolean showVip) {
        content_buffer = new StringBuffer();
        for (String item : tags) {//将每个tag的内容添加到content后边，之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }

        if (showVip) {
            content_buffer.append("     ");
        }

        content_buffer.append(content);
        int endIndex = 0;
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_tag, null);//R.layout.tag是每个标签的布局
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(item);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());//缺少这句的话，不会报错，但是图片不回显示
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);//图片将对齐底部边线
            int startIndex;
            startIndex = getLastLength(tags, i);
            endIndex = startIndex + item.length();
            if (!TextUtils.isEmpty(item)) {
                endIndex = startIndex + item.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        if (showVip) {
            Drawable drawable = this.getResources().getDrawable(R.mipmap.details_vip_icon);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            spannableString.setSpan(imageSpan, endIndex, endIndex + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }

    public void setContentAndTag(String content, List<String> tags, boolean showVip, boolean isPurchase) {
        content_buffer = new StringBuffer();
        for (String item : tags) {//将每个tag的内容添加到content后边，之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }

        if (showVip) {
            content_buffer.append("     ");
        }

        content_buffer.append(content);
        int endIndex = 0;
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            View view;
            if (isPurchase){
                view = LayoutInflater.from(mContext).inflate(R.layout.view_purchase_tag, null);//R.layout.tag是每个标签的布局
            }else {
                view = LayoutInflater.from(mContext).inflate(R.layout.view_tag, null);//R.layout.tag是每个标签的布局
            }
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(item);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());//缺少这句的话，不会报错，但是图片不回显示
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);//图片将对齐底部边线
            int startIndex;
            startIndex = getLastLength(tags, i);
            endIndex = startIndex + item.length();
            if (!TextUtils.isEmpty(item)) {
                endIndex = startIndex + item.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        if (showVip) {
            Drawable drawable = this.getResources().getDrawable(R.mipmap.details_vip_icon);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            spannableString.setSpan(imageSpan, endIndex, endIndex + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }

    public void setContentAndImgTag(String content, String country, String country_logo, String country_tag, String shop_icon) {
        content_buffer = new StringBuffer();
        List<String> tags = new ArrayList<>();
        if (!TextUtils.isEmpty(country)) {
            tags.add("country");
        }
        if (!TextUtils.isEmpty(shop_icon)) {
            tags.add("shop_icon");
        }
        for (String item : tags) {//将每个tag的内容添加到content后边，之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }
        content_buffer.append(content);
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            if (item.equals("country")) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.view_overseas_tag, null);//R.layout.tag是每个标签的布局
                ImageView img = view.findViewById(R.id.overseas_direct_mail_icon);
                TextView tvName = view.findViewById(R.id.overseas_direct_mail_name);
                ViewTransformUtil.glideImageView(mContext, country_logo, img,
                        new CropCircleWithBorderTransformation(0, mContext.getResources().getColor(R.color.white)), R.mipmap.defaults);
                tvName.setText(country);
                tvName.setMaxEms(!TextUtils.isEmpty(country_tag) && "2".equals(country_tag) ? 4 : 20);
                Bitmap bitmap = convertViewToBitmap(view);
                Drawable d = new BitmapDrawable(bitmap);
                d.setBounds(0, 0, view.getWidth(), view.getHeight());//缺少这句的话，不会报错，但是图片不回显示
                CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);//图片将对齐底部边线
                int startIndex;
                int endIndex;
                startIndex = getLastLength(tags, i);
                if (!TextUtils.isEmpty(item)) {
                    endIndex = startIndex + item.length();
                } else {
                    endIndex = startIndex;
                }
                Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
                spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                View view = LayoutInflater.from(mContext).inflate(R.layout.view_img_tag, null);//R.layout.tag是每个标签的布局
                img_tag = view.findViewById(R.id.img_tag);
                ViewTransformUtil.glideImageView(mContext, shop_icon, img_tag, R.mipmap.defaults);
                Bitmap bitmap = convertViewToBitmap(view);
                Drawable d = new BitmapDrawable(bitmap);
                d.setBounds(0, 0, img_tag.getWidth(), img_tag.getHeight());//缺少这句的话，不会报错，但是图片不回显示
                CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);//图片将对齐底部边线
                int startIndex;
                int endIndex;
                startIndex = getLastLength(tags, i);
                if (!TextUtils.isEmpty(item)) {
                    endIndex = startIndex + item.length();
                } else {
                    endIndex = startIndex;
                }
                Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
                spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        setText(spannableString);
    }

    public void setContentAndTag(String content, List<String> tags, int resource) {
        content_buffer = new StringBuffer();
        for (String item : tags) {//将每个tag的内容添加到content后边，之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }
        content_buffer.append(content);
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            View view = LayoutInflater.from(mContext).inflate(resource, null);//R.layout.tag是每个标签的布局
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(item);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());//缺少这句的话，不会报错，但是图片不回显示
            CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);//图片将对齐底部边线
            int startIndex;
            int endIndex;
            startIndex = getLastLength(tags, i);
            if (!TextUtils.isEmpty(item)) {
                endIndex = startIndex + item.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }

    //全球购
    public void setContentAndTag(String content, List<String> tags, int resource, boolean showVip) {
        content_buffer = new StringBuffer();
        for (String item : tags) {//将每个tag的内容添加到content后边，之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }
        if (showVip) {
            content_buffer.append("     ");
        }
        content_buffer.append(content);
        int endIndex = 0;
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            View view = LayoutInflater.from(mContext).inflate(resource, null);//R.layout.tag是每个标签的布局
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(item);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());//缺少这句的话，不会报错，但是图片不回显示
            CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);//图片将对齐底部边线
            int startIndex;
            startIndex = getLastLength(tags, i);
            if (!TextUtils.isEmpty(item)) {
                endIndex = startIndex + item.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (showVip) {
            Drawable drawable = this.getResources().getDrawable(R.mipmap.details_vip_icon);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            spannableString.setSpan(imageSpan, endIndex, endIndex + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }


    public void setContentCommodityDetails(String content, String oversea, String vipExclusive) {
        content_buffer = new StringBuffer();
        content_buffer.append(oversea + " ");
        content_buffer.append(vipExclusive);

        content_buffer.append(content);
        SpannableString spannableString = new SpannableString(content_buffer);
        if (!TextUtils.isEmpty(oversea)) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_good_detail_tag, null);
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(oversea);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());
            CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);
            int startIndex;
            int endIndex;
            startIndex = 0;
            if (!TextUtils.isEmpty(oversea)) {
                endIndex = startIndex + oversea.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!TextUtils.isEmpty(vipExclusive)) {
            ImageView img = new ImageView(mContext);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ScreenUtils.dp2px(59), ScreenUtils.dp2px(16));
            img.setLayoutParams(layoutParams);
            Glide.with(mContext).asBitmap().load(R.mipmap.details_vip_icon).into(img);
            Bitmap bitmap = convertViewToBitmap(img);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, img.getWidth(), img.getHeight());
            CenteredImageSpan span = new CenteredImageSpan(mContext, bitmap);
            int startIndex;
            int endIndex;
            startIndex = oversea.length() + 1;
            if (!TextUtils.isEmpty(vipExclusive)) {
                endIndex = startIndex + vipExclusive.length();
            } else {
                endIndex = startIndex;
            }
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }


    private static Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        Bitmap bitmap = view.getDrawingCache();


        return bitmap;

    }


    private int getLastLength(List<String> list, int maxLength) {
        int length = 0;
        for (int i = 0; i < maxLength; i++) {
            length += list.get(i).length();
        }
        return length;
    }


    public class CenterAlignImageSpan extends ImageSpan {

        public CenterAlignImageSpan(Drawable d) {
            super(d);
        }

        public CenterAlignImageSpan(Drawable d, int verticalAlignment) {
            super(d, verticalAlignment);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom,
                         Paint paint) {
            Drawable drawable = getDrawable();
            Paint.FontMetricsInt fm = paint.getFontMetricsInt();
            //计算y方向的位移
            int translationY = (y + fm.descent + y + fm.ascent) / 2 - drawable.getBounds().bottom / 2;
            canvas.save();
            //绘制图片位移一段距离
            canvas.translate(x, translationY);
            drawable.draw(canvas);
            canvas.restore();
        }
    }
}

